<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AJAX POST 请求</title>
    <style>
        #result {
            width: 200px;
            height: 100px;
            border: solid 1px #90b
        }
    </style>
</head>

<body>
    <div id="result"></div>
</body>
<script lang="javascript">
    const BASE_URL = "http://localhost:8000"
    // get button element
    const result = document.getElementById("result");
    var param = {
            'name':'Tom',
            'age':'13'
        }
    // bind action to element
    result.addEventListener("mouseover", () => {
        // 1. create object 
        const xhr = new XMLHttpRequest();
        // 2. initialization set request method and url
        xhr.open('post', BASE_URL + '/server', true);
        // 3. send
        // set request header 
        // x-www-form-urlencoded
        xhr.setRequestHeader("content-type","application/json");
        xhr.setRequestHeader("collins","yes")
        // xhr.setRequestHeader('Access-Control-Allow-Origin','*');
        // xhr.setRequestHeader('Access-Control-Allow-Methods','GET,POST,OPTIONS');
        // xhr.setRequestHeader('Access-Control-Allow-Headers','Content-Type, Authorization')
        xhr.send(JSON.stringify(param));
        // 4. deal with response
        xhr.onreadystatechange = function(){
            if(xhr.readyState === 4){
                if(xhr.status >= 200 && xhr.status < 300){
                    // handle result
                    result.innerHTML = xhr.response;
                }else{
                    
                }

            }
        }

    })
</script>

</html>